package com.oneplatform.cms.service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jeesuite.common.util.AssertUtil;
import com.jeesuite.common.util.BeanUtils;
import com.jeesuite.mybatis.plugin.pagination.Page;
import com.jeesuite.mybatis.plugin.pagination.PageExecutor;
import com.jeesuite.mybatis.plugin.pagination.PageExecutor.PageDataLoader;
import com.jeesuite.mybatis.plugin.pagination.PageParams;
import com.oneplatform.cms.dao.entity.ArticleEntity;
import com.oneplatform.cms.dao.entity.CategoryEntity;
import com.oneplatform.cms.dao.mapper.ArticleEntityMapper;
import com.oneplatform.cms.dao.mapper.CategoryEntityMapper;
import com.oneplatform.cms.dto.param.ArticleQueryParam;

/**
 * generated by www.jeesuite.com
 */
@Service
public class ArticleService {

	@Autowired
	private ArticleEntityMapper cmsArticleMapper;
	private @Autowired CategoryEntityMapper categoryMapper;

	public void addCmsArticle(ArticleEntity entity) {
		cmsArticleMapper.insertSelective(entity);
	}

	public void updateCmsArticle(ArticleEntity entity) {
		ArticleEntity originEntity = cmsArticleMapper.selectByPrimaryKey(entity.getId());
		AssertUtil.notNull(originEntity);
		BeanUtils.copy(entity, originEntity);
		cmsArticleMapper.updateByPrimaryKey(originEntity);
	}
	
	public void deleteCmsArticle(Integer id) {
		cmsArticleMapper.deleteByPrimaryKey(id);
	}
	
	public ArticleEntity findCmsArticleById(Integer id){
		ArticleEntity entity = cmsArticleMapper.selectByPrimaryKey(id);
		AssertUtil.notNull(entity);
		return entity;
	}
	
    public Page<ArticleEntity> pageQuery(PageParams pageParam,ArticleQueryParam param){
		Page<ArticleEntity> page = PageExecutor.pagination(pageParam, new PageDataLoader<ArticleEntity>() {
			@Override
			public List<ArticleEntity> load() {
				return cmsArticleMapper.findListByQueryParam(param);
			}
		});
		
		if(page.getTotal() > 0){
			Map<Integer, CategoryEntity> categoryMap = categoryMapper.selectAll().stream().collect(Collectors.toMap(CategoryEntity::getId, e -> e));
		   for (ArticleEntity article : page.getData()) {
			   article.setCategoryName(categoryMap.get(article.getCategoryId()).getName());
		   }
		}
		return page;
	}

}
